//
//  InsetsLabel.swift
//  CustomInsetsLabel
//
//  Created by 李煜 on 2024/9/12.
//https://www.jianshu.com/p/61716d7b6b57

import UIKit

class InsetsLabel: UILabel {
  var insets: UIEdgeInsets = .zero
  
  //重写固有尺寸,把insets考虑进去
  override var intrinsicContentSize: CGSize {
    var size = super.intrinsicContentSize
    size.width += insets.left + insets.right
    size.height += insets.top + insets.bottom

    return size
  }
  
  //重写渲染区域,把insets考虑进去
  override func drawText(in rect: CGRect) {
    // 在rect周围添加边距
    // =UIEdgeInsetsInsetRect(rect, self.insets)
    super.drawText(in: rect.inset(by: insets))
  }

  //重写sizeToFit自适应方法,把insets考虑进去
  override func sizeThatFits(_ size: CGSize) -> CGSize {
    //拿到系统计算的adjustSize
    let adjustSize = super.sizeThatFits(size)
    //在其基础之上+insets
    let widthInsets = adjustSize.width + insets.horizontalInsets;
    let heightInsets = adjustSize.height + insets.verticalInsets;
    
    return CGSize(width: widthInsets, height: heightInsets)
  }
  override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
    print("----\(self.tag)----")
    print(bounds)
    let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
    print(rect)
    return rect
  }
  override func layoutSubviews() {
    super.layoutSubviews()
    
  }
  
}
extension UIEdgeInsets {
  var horizontalInsets: CGFloat {
    return self.left + self.right;
  }
  var verticalInsets: CGFloat {
    return self.top + self.bottom;
  }
}
